import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo_2025_1/entity/my_location.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class ShareLocation extends StatefulWidget {
  const ShareLocation({super.key});
  @override
  State<StatefulWidget> createState() {
    return _ShareLocationState();
  }
}

class _ShareLocationState extends State<ShareLocation> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String? _streetName;
  File? _image;
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
  }

  Future<void> _getCurrentLocation() async {
    try {
      Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high,
      );
      List<Placemark> placemarks = await placemarkFromCoordinates(
        position.latitude,
        position.longitude,
      );
      setState(() {
        _streetName = placemarks.first.street;
      });
    } catch (e) {
      print('Error getting location: $e');
    }
  }

  Future<void> _pickImage([ImageSource imageSource = ImageSource.gallery]) async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: imageSource);
    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });
    }
  }

  Future<void> _submitForm() async {
    if (_formKey.currentState!.validate()) {
      MyLocation location = MyLocation(
        title: _titleController.text ?? '',
        desc: _descriptionController.text ?? '',
        image: _image?.path ?? ''
      );
      LocationList.setStorage(location);
      Navigator.pop(context, { 'code': 1 });
    }
  }

  @override
  Widget build(BuildContext context) {
    double _commonPadding = 12.w;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF003a8c),
        foregroundColor: Colors.white,
        title: Text('分享新地点')
      ),
      body: SafeArea(
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              Card(
                color: Theme.of(context).cardColor,
                child: Padding(
                  padding: EdgeInsets.all(_commonPadding),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      if (_streetName != null)
                        Text('当前街道: $_streetName'),
                      SizedBox(height: _commonPadding),
                      TextFormField(
                        controller: _titleController,
                        decoration: const InputDecoration(labelText: '标题', hintText: '请输入标题'),
                        autovalidateMode: AutovalidateMode.onUserInteraction,
                        validator: (String? value) {
                          if (value == null || value.isEmpty) {
                            return '请输入一个标题';
                          }
                          return null;
                        },
                      ),
                      SizedBox(height: _commonPadding),
                      TextFormField(
                        controller: _descriptionController,
                        decoration: const InputDecoration(labelText: '描述', hintText: '请输入描述'),
                        maxLines: 3,
                      ),
                    ],
                  ),
                ),
              ),
              Card(
                color: Theme.of(context).cardColor,
                child: Padding(
                  padding: EdgeInsets.all(_commonPadding),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Text('附图'),
                      Stack(
                        children: [
                          Container(
                            padding: EdgeInsets.all(_commonPadding),
                            child: _image != null ? Image.file(
                              _image!,
                              height: 200.h,
                              width: 360.w,
                              fit: BoxFit.cover,
                            ) : SizedBox(width: 360.w,height: 200.h,),
                          ),
                          Positioned(
                            top: 0,
                            right: 0,
                            child: MenuAnchor(
                              builder: (context, controller, child) {
                                return IconButton(
                                  onPressed: () {
                                    if (controller.isOpen) {
                                      controller.close();
                                    } else {
                                      controller.open();
                                    }
                                  },
                                  icon: const Icon(Icons.more_vert),
                                );
                              },
                              menuChildren: [
                                MenuItemButton(child: const Text('相册'), onPressed: () { _pickImage(ImageSource.gallery); }),
                                MenuItemButton(child: const Text('拍照'), onPressed: () { _pickImage(ImageSource.camera); })
                              ],
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: _commonPadding),
                      ElevatedButton(
                        onPressed: _submitForm,
                        child: Text('提交'),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}